package org.example.rabbitmq;

import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j;
import org.example.config.RabbitmqTwoConfig;
import org.example.socket.webSocketMessage;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Set;


@Component
@Log4j
public class messageFromBack {
    @Autowired
    private webSocketMessage webSocketMessage;
    @RabbitListener(queues = RabbitmqTwoConfig.QUEUE_SEND_MESSAGE, containerFactory = "twoFactory")
    public void addUserConsumer(String obj,Message msg, Channel channel) {
        Set<String> strings = org.example.socket.webSocketMessage.SESSION_POOL.keySet();
        //TODO 离线推送消息

        webSocketMessage.sendAllMessage(obj);
        extracted(obj,msg,channel);

    }

    private void extracted(String obj,Message msg, Channel channel) {
        long deliverTag = msg.getMessageProperties().getDeliveryTag();
        try {
            //业务逻辑代码...
            log.error(obj);
            //消费成功，确认消息
            channel.basicAck(deliverTag, true);
        }catch (Exception e){
            //拒绝消息,为true会重新放回队列（自定义拒绝规则，比如：redis计数，消费5次后依然报错失败则拒绝）
            try {
                channel.basicReject(deliverTag, false);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            try {
                //nack返回false，并重新回到队列
                channel.basicNack(deliverTag, false, true);
            } catch (IOException ioException) {

                log.error(e.getMessage(),e);
            }
            log.error(e.getMessage(),e);


        }
    }
}
